package com.example.rabbitmq.bugtest1;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;

/**
 * @author audy
 * @description: TODO
 * @date 2022/8/7 22:11
 *
 * 使用rabbitmq实现异步处理，但要考虑消息丢失的情况，该示例用于演示该问题的处理方法：补偿或者说建立主备双活流程
 * */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private UserService userService;

    @GetMapping("register")
    public void register() {
        IntStream.rangeClosed(1, 10).forEach(i -> {
            User user = userService.register();
            if (ThreadLocalRandom.current().nextInt(10) % 2 == 0) {
                rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE, RabbitConfig.ROUTING_KEY, user);
                log.info("sent mq user {}", user.getId());
            }
        });
    }
}
